package com.yx.front.manager;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.yx.front.config.global.BizException;
import com.yx.front.config.global.CommonResult;
import com.yx.front.enums.NoticeType;
import com.yx.front.enums.TimeFormat;
import com.yx.front.model.SysUser;
import com.yx.front.model.SystemNotice;
import com.yx.front.model.param.SystemNoticeParam;
import com.yx.front.model.vo.SystemNoticeVo;
import com.yx.front.service.SystemNoticeService;
import com.yx.front.utils.LoginUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author YangXiong
 */
@Component
public class SystemNoticeManager {
    @Resource
    private SystemNoticeService systemNoticeService;
    @Resource
    private LoginUtil loginUtil;

    public CommonResult<String> save(SystemNoticeParam param) {
        if(StringUtils.isEmpty(param.getContext())){
            throw new BizException("内容不能为空");
        }
        SysUser currentUser = loginUtil.getCurrentUser();
        SystemNotice notice = new SystemNotice();
        notice.setContext(param.getContext());
        notice.setFromId(currentUser.getId());
        notice.setOperatorId(currentUser.getId());
        notice.setOperatorName(currentUser.getUserName());
        notice.setToId(null);
        notice.setCreateTime(DateUtil.date());
        notice.setModifyTime(DateUtil.date());
        notice.setType(NoticeType.TO_SYSTEM.getCode());
        boolean save = systemNoticeService.save(notice);
        if(save){
            return CommonResult.success("感谢您的建议，我们会努力改进");
        }
        return CommonResult.fail("系统异常，请稍后再试");
    }

    public CommonResult<List<SystemNoticeVo>> getHistory() {
        SysUser currentUser = loginUtil.getCurrentUser();
        LambdaQueryWrapper<SystemNotice> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SystemNotice::getFromId, currentUser.getId());
        wrapper.orderByDesc(SystemNotice::getCreateTime);
        List<SystemNotice> list = systemNoticeService.list(wrapper);
        return CommonResult.success(handlerResult(list));
    }

    private List<SystemNoticeVo> handlerResult(List<SystemNotice> list) {
        List<SystemNoticeVo> vos = new ArrayList<>();
        list.forEach(one->{
            SystemNoticeVo vo = new SystemNoticeVo();
            vo.setId(one.getId());
            vo.setContext(one.getContext());
            vo.setCreateTime(DateUtil.format(one.getCreateTime(), TimeFormat.TIME_FORMAT));
            vos.add(vo);
        });
        return vos;
    }
}